package com.example.security.assembly;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.base.dto.TokenUserDTO;
import com.example.security.utils.SecurityUserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 实体类更新插入默认数据
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        TokenUserDTO user = SecurityUserUtil.getNowUser();
        if (Objects.isNull(user)){
            return;
        }
        this.strictInsertFill(metaObject, "create_by", Long.class, user.getUserId());
        this.strictInsertFill(metaObject, "create_name", String.class, user.getUserName());
        this.strictInsertFill(metaObject, "create_time", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        TokenUserDTO user = SecurityUserUtil.getNowUser();
        if (Objects.isNull(user)){
            return;
        }
        this.strictInsertFill(metaObject, "update_by", Long.class, user.getUserId());
        this.strictInsertFill(metaObject, "update_name", String.class, user.getUserName());
        this.strictInsertFill(metaObject, "update_time", LocalDateTime.class, LocalDateTime.now());
    }
}
